(function() {
	var $ = require(L('$')), _ = require(L('_'));

	var win = $.createWindow(L('win_product_details'));
	win.navbar = $.ui('navbar')(true, true);
	var ui = $.layout('product_details/view');
	ui.top.add($.ui('partial').scan_and_take_photo());
	win.add([win.navbar, ui.view]);

	win.display = function(productVariantID, retailerStoreID, canGoBack, isScaned) {
		canGoBack = canGoBack === false ? false : true;
		isScaned = isScaned != true? false : true;
		win.navbar.update(canGoBack, true);
		$.opacity_show(ui.view, false);
		$.mask();
		$.webservice().getProductDetails(productVariantID, retailerStoreID, isScaned, function(e) {
			var product = JSON.parse(e);
			$.removeChildren(ui.content);
			ui.content.add(Layout(product));
			$.mask(false);
			$.opacity_show(ui.view);
		});
	};

	function Layout(product) {
		var viewProductDetails = partial.expandable('Product details', partial.description(product, false, function() {
			$.repeat(function() {
				$.updateHeight([viewProductDetails.child, ui.view]);
			}, 10);
		}));
		if (product.HaveOffer) {
			if (product.BundledProductVariantName) {
				var ui = $.layout('product_details/bundle_offer');
				ui.title.text = product.OfferName;
				ui.partials.add(partial.expandable(product.Name, partial.images_and_attributes(product, 1)));
				ui.partials.add(partial.expandable(product.BundledProductVariantName, partial.images_and_attributes(product, 2), true));
				ui.partials.add(partial.offer_info(product));
				ui.partials.add(partial.btn_add_to_cart(product));
				var viewOfferDetails = partial.expandable('Offer details', partial.description(product, true, function() {
					$.repeat(function() {
						$.updateHeight([viewOfferDetails.child, ui.view]);
					}, 10);
				}));
				ui.partials.add([viewProductDetails, viewOfferDetails]);
			} else {
				var ui = $.layout('product_details/single_offer');
				ui.title.text = product.OfferName;
				ui.partials.add(partial.images_and_attributes(product, 1));
				ui.partials.add(partial.offer_info(product));
				ui.partials.add(partial.btn_add_to_cart(product));
				var viewOfferDetails = partial.expandable('Offer details', partial.description(product, true, function() {
					$.repeat(function() {
						$.updateHeight([viewOfferDetails.child, ui.view]);
					}, 10);
				}));
				ui.partials.add([viewProductDetails, viewOfferDetails]);
			}
		} else {
			var ui = $.layout('product_details/normal');
			ui.title.text = product.Name;
			ui.partials.add(partial.images_and_attributes(product, 1));
			ui.partials.add(partial.btn_add_to_cart(product));
			ui.partials.add([viewProductDetails]);
		}
		//ui.retailerLogo.image = product.RetailerLogo;
		$.cache_image(product.RetailerLogo, ui.retailerLogo);
		return ui.view;
	};

	var partial = {};
	partial.attribute = function(name, value, isOrange) {
		var pui = $.layout('product_details/partial/attribute');
		pui.name.text = name;
		pui.value.text = value;
		if (isOrange) {
			pui.name.color = L('color_orange');
			pui.value.color = L('color_orange');
			pui.view.top = 10;
		}
		return pui.view;
	};
	partial.description = function(product, offerDetails, onLoad) {
		var view = $.createWebView('data/html/product_details_description.html', {
			scalePageToFit : false,
			width : 280,
			height : 'auto',
			top : 0,
			hideShadow : true,
			font : {
				fontSize : '14dip',
			}
		});
		view.onload(function() {
			if (offerDetails) {
				view.css('br1', 'display', 'none');
				view.css('br2', 'display', 'none');
				view.val('coreProductDescription', product.OfferDescription);
			} else if (product.HaveOffer && product.BundledProductVariantName) {
				view.val('coreProductName', product.Name);
				view.val('coreProductDescription', product.Description);
				view.val('bundledProductName', product.BundledProductVariantName);
				view.val('bundledProductDescription', product.BundledProductVariantDescription);
			} else {
				view.css('br1', 'display', 'none');
				view.css('br2', 'display', 'none');
				view.val('coreProductDescription', product.Description);
			}
			view.height = view.evalJS("document.getElementById('container').offsetHeight;");
			onLoad && onLoad();
		});
		return view;
	};
	partial.expandable = function(title, childView, expandDefault) {
		title = title.length > 28 ? title.substring(0, 28) + '...' : title;
		var pui = $.layout('product_details/partial/expandable');
		pui.title.text += title;
		$.click(pui.title, function() {
			if (pui.title.expanded == true) {
				pui.title.backgroundImage = L('bg_arrow_right');
				if (childView)
					pui.child.remove(childView);
				$.updateHeight([pui.child, ui.view]);
				pui.title.expanded = false;
			} else {
				pui.title.backgroundImage = L('bg_arrow_down');
				if (childView)
					pui.child.add(childView);
				$.updateHeight([pui.child, ui.view]);
				pui.title.expanded = true;
			}
		});
		if (expandDefault) {
			pui.title.backgroundImage = L('bg_arrow_down');
			if (childView)
				pui.child.add(childView);
			$.updateHeight([pui.child, ui.view]);
			pui.title.expanded = true;
		}
		pui.view.child = pui.child;
		return pui.view;
	};
	partial.images = function(images) {
		var ui = $.layout('product_details/partial/images');
		ui.slider.addEventListener('twofingertap', function() {
			return false;
		});
		var data = new Array();
		ui.customPaging.activeItem = function(index) {
			if (ui.customPaging.children) {
				for (var i = 0, j = ui.customPaging.children.length; i < j; i++) {
					ui.customPaging.children[i].image = i == index ? L('icon_dot_on') : L('icon_dot');
				}
			}
		};
		_.each(images, function(image) {
			var imageView = Ti.UI.createImageView({
				width : 'auto',
				height : '110dip',
				// image : image.MediumImage
			});
			$.cache_image(image.MediumImage, imageView);
			data.push(imageView);
			ui.customPaging.add(Ti.UI.createImageView({
				width : '15dip',
				height : '15dip',
				left : '5dip'
			}));
		});
		var firstImage = data[0];
		if (!$.isNull(firstImage)) {
			firstImage.visible = false;
			firstImage.addEventListener('load', function() {
				firstImage.visible = true;
			});
		}
		ui.slider.views = data;
		ui.customPaging.activeItem(0);
		ui.slider.addEventListener('scroll', function(e) {
			ui.customPaging.activeItem(e.currentPage);
		});
		return ui.view;
	};
	partial.images_and_attributes = function(product, type) {
		var pui = $.layout('product_details/partial/images_and_attributes');
		var images = type == 1 ? product.Images : product.BundledProductVariantImages;
		var attributes = type == 1 ? product.AttributeGroup : product.BundledProductVariantAttributeGroup;
		var pinterestShared = type == 1 ? product.PinterestShared : product.BundledPinterestShared;
		var fbShared = type == 1 ? product.FBShared : product.BundledFBShared;
		var twitterShared = type == 1 ? product.TwitterShared : product.BundledTwitterShared;
		var emailShared = type == 1 ? product.EmailShared : product.BundledEmailShared;

		var shareFbLink = type == 1 ? product.ShareFbLink : product.ShareFbLink;
		var shareFbName = type == 1 ? product.ShareFbName : product.BundledProductShareFbName;
		var shareFbCaption = type == 1 ? product.ShareFbCaption : product.BundledProductShareFbCaption;
		var shareFbDescription = type == 1 ? product.ShareFbDescription : product.ShareFbDescription;
		var shareFbPicture = product.ShareFbPicture;
		if (type == 2 && product.BundledProductVariantImages && product.BundledProductVariantImages[0])
			shareFbPicture = product.BundledProductVariantImages[0].MediumImage;
		var shareTwitterMessage = type == 1 ? product.ShareTwitterMessage : product.BundledProductShareTwitterMessage;
		var sharePinterestDescription = type == 1 ? product.SharePinterestDescription : product.SharePinterestDescription;
		var productVariantID = type == 1 ? product.ProductVariantID : product.BundledProductVariantID;
		var coreProductVariantID = type == 1 ? '' : product.ProductVariantID;
		var retailerStoreID = type == 1 ? product.RetailerStoreID : product.RetailerStoreID;

		$.tap(pui.share, function() {
			$.ui('popup').share({
				fb : {
					link : shareFbLink,
					name : shareFbName,
					message : shareFbCaption,
					caption : '',
					description : shareFbDescription,
					picture : product.ShareFbPicture,
				},
				twitter : {
					message : shareTwitterMessage
				},
				pinterest : {
					link : shareFbLink,
					picture : shareFbPicture,
					description : sharePinterestDescription
				},
				email : {
					productVariantID : productVariantID,
					retailerStoreID : retailerStoreID
				}
			}, function(e) {
				$.needToReloadMyDesires(true);
				if (e == $.enum('share').Pinterest)
					pui.iconPinterest.image = L('icon_pinterest_on');
				if (e == $.enum('share').Facebook)
					pui.iconFacebook.image = L('icon_facebook_on');
				if (e == $.enum('share').Twitter)
					pui.iconTwitter.image = L('icon_twitter_on');
				if (e == $.enum('share').Email) {
					pui.iconEmail.image = L('icon_email_on');
					return;
				}
				$.webservice().updateShareInfo(productVariantID, retailerStoreID, e, coreProductVariantID, function(response) {
					var result = JSON.parse(response);
					if (result.Success) {
						$.a(L('message_share_success'), L('message_share_success_title'));
					}
				});
			}).open();
		});

		pui.images.add(partial.images(images));
		_.each(attributes, function(attr) {
			var value = _.find(attr.Values, function(value) {
				return value.IsSelected == true;
			});
			pui.attributes.add(partial.attribute(attr.Name, value.Value));
		});
		if (type == 1) {
			pui.attributes.add(partial.attribute('Price', product.FormattedPrice, true));
		}
		if (pinterestShared)
			pui.iconPinterest.image = L('icon_pinterest_on');
		if (fbShared)
			pui.iconFacebook.image = L('icon_facebook_on');
		if (twitterShared)
			pui.iconTwitter.image = L('icon_twitter_on');
		if (emailShared)
			pui.iconEmail.image = L('icon_email_on');
		return pui.view;
	};
	partial.btn_add_to_cart = function(product) {
		var pui = $.layout('product_details/partial/btn_add_to_cart');
		$.tap(pui.view, function() {
			var saleCampaignID = product.HaveOffer ? product.SaleCampaignOfferCustomerDefinedBundleID : '';
			$.addToShoppingBag(product.ProductVariantID, product.RetailerStoreID, saleCampaignID);
		});
		return pui.view;
	};
	partial.offer_info = function(product) {
		var view = $.createWebView('data/html/product_details_offer_info.html', {
			width : 280,
			height : 120,
			right : 0,
			top : 5
		});
		view.onload(function() {
			view.val('val_1', product.FormattedOfferNormalPrice);
			view.val('val_3', product.FormattedOfferedPrice);
			// view.val('val_4', product.OfferTimeleft);
			// $.w(product.OfferEndDateString + ' # ' +$.calculateOfferTimeLeft(product.OfferEndDateString));
			view.val('val_4', $.calculateOfferTimeLeft(product.OfferEndDateString));
			view.val('val_2', '-$' + (product.OfferNormalPrice - product.OfferedPrice).toFixed(2));
		});
		view.addEventListener("touchmove", function(e) {
			return false;
		});
		return view;
	};

	module.exports = win;
})();
